package com.tarena.luban.demo.gateway.handler;

import com.tarena.luban.demo.gateway.ex.GatewayException;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;

@Component
public class MyErrorHandler implements ErrorWebExceptionHandler {
    /**
     * @param exchange 抛出异常的某个请求链
     * @param ex 异常具体对象
     * @return
     */
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        String message=null;
        if (ex instanceof GatewayException){
            //认证失败
            GatewayException e=(GatewayException)ex;
            message=e.getMessage();
        }else{
            //不是业务异常
            message="系统异常";
        }
        ServerHttpResponse response = exchange.getResponse();
        byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
        return response.writeWith(Mono.fromSupplier(() -> response.bufferFactory().wrap(bytes)));
    }
}
